package net.zoneland.zrdp.web.endpoint;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.GetMapping;

import com.branchitech.utils.SystemHelper;
import com.github.pagehelper.dialect.AbstractHelperDialect;
import com.google.common.collect.Maps;

import net.zoneland.zrdp.common.core.domain.model.LoginUser;
import net.zoneland.zrdp.framework.web.service.TokenService;

/**
 * 开发相关服务.
 * -Dzrdp.dev.endpointOn=true
 * @author zonevue
 */
@RestControllerEndpoint(id = "zrdpdev")
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(prefix = "zrdp.dev", name = "endpointOn", havingValue = "true", matchIfMissing = false)
public class ZrdpDevEndpoint {

    @Resource
    private TokenService tokenService;

    @GetMapping("")
    public Map<String, Object> index() {
        final Map<String, Object> ret = Maps.newHashMap();
        ret.put("pagehelperSqlParseCacheOn", "enable=true/false");
        ret.put("getLoginUser", "");
        return ret;
    }

    // /actuator/zrdpdev/getLoginUser
    @GetMapping("getLoginUser")
    public LoginUser getLoginUser(final HttpServletRequest request) {
        return tokenService.getLoginUser(request);
    }

    @GetMapping("getSessionAttribute")
    public Object getSessionAttribute(final HttpServletRequest request, final String key) {
        final HttpSession session = request.getSession(false);
        return session == null ? null : session.getAttribute(key);
    }

    // /actuator/zrdpdev/pagehelperSqlParseCacheOn?enable=true/false
    @GetMapping("pagehelperSqlParseCacheOn")
    public Object pagehelperSqlParseCacheOn(final String enable) {
        if (StringUtils.isNoneBlank(enable)) {
            final Boolean flag = Boolean.valueOf(enable);
            SystemHelper.setStaticFieldValue(AbstractHelperDialect.class, "cacheOnFlag", flag);
            SystemHelper.setStaticFieldValue(AbstractHelperDialect.class, "tracingOn", Boolean.TRUE);
        }
        return SystemHelper.getStaticFieldValue(AbstractHelperDialect.class, "cacheOnFlag");
    }
}
